package com.apkicon.test;

import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.bean.ApkMeta;
import com.apkicon.parser.ApkResourceResolver;
import com.apkicon.parser.ResourcesArscParser;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * 前景图片提取器 - 专门提取foreground原始PNG
 */
public class ForegroundExtractor {
    
    public static void main(String[] args) {
        String apkPath = "test.apk";
        
        try (ApkFile apkFile = new ApkFile(apkPath)) {
            System.out.println("🔍 提取前景图片: " + apkPath);
            
            // 1. 解析APK基本信息
            ApkMeta apkMeta = apkFile.getApkMeta();
            System.out.println("📱 应用信息:");
            System.out.println("   包名: " + apkMeta.getPackageName());
            System.out.println("   版本: " + apkMeta.getVersionName() + " (" + apkMeta.getVersionCode() + ")");
            System.out.println("   应用名称: " + apkMeta.getLabel());
            
            // 2. 获取图标路径
            String iconPath = apkMeta.getIcon();
            System.out.println("🎯 图标路径: " + iconPath);
            
            // 3. 解析Adaptive Icon资源
            System.out.println("🔍 解析Adaptive Icon资源: " + iconPath);
            ApkResourceResolver.AdaptiveIconResources resources = ApkResourceResolver.resolveAdaptiveIconResources(apkFile, iconPath);
            
            // 4. 提取前景图片
            String foregroundPath = resources.getForegroundPath();
            System.out.println("🖼️ 前景资源路径: " + foregroundPath);
            
            if (foregroundPath != null) {
                // 5. 从APK中读取前景图片
                byte[] foregroundData = apkFile.getFileData(foregroundPath);
                if (foregroundData != null) {
                    System.out.println("✅ 找到前景文件: " + foregroundPath + " (" + foregroundData.length + " bytes)");
                    
                    // 6. 保存为PNG文件
                    BufferedImage foregroundImage = ImageIO.read(new ByteArrayInputStream(foregroundData));
                    if (foregroundImage != null) {
                        System.out.println("📐 前景图片尺寸: " + foregroundImage.getWidth() + "x" + foregroundImage.getHeight());
                        
                        // 保存原始前景图片
                        File outputFile = new File("foreground_original.png");
                        ImageIO.write(foregroundImage, "PNG", outputFile);
                        System.out.println("✅ 前景图片已保存: " + outputFile.getName());
                        
                        // 如果是9-patch图片，也保存一个处理后的版本
                        if (foregroundPath.endsWith(".9.png")) {
                            System.out.println("🔧 检测到9-patch图片，创建处理后版本...");
                            BufferedImage processedImage = processNinePatchImage(foregroundImage);
                            File processedFile = new File("foreground_processed.png");
                            ImageIO.write(processedImage, "PNG", processedFile);
                            System.out.println("✅ 处理后前景图片已保存: " + processedFile.getName());
                        }
                        
                        // 创建放大版本用于查看细节
                        BufferedImage enlargedImage = enlargeImage(foregroundImage, 4);
                        File enlargedFile = new File("foreground_enlarged.png");
                        ImageIO.write(enlargedImage, "PNG", enlargedFile);
                        System.out.println("✅ 放大版前景图片已保存: " + enlargedFile.getName());
                        
                    } else {
                        System.err.println("❌ 无法读取前景图片数据");
                    }
                } else {
                    System.err.println("❌ 未找到前景文件: " + foregroundPath);
                }
            } else {
                System.err.println("❌ 未找到前景资源路径");
            }
            
            // 7. 显示所有找到的前景资源
            System.out.println("\n🔍 前景资源信息:");
            System.out.println("   背景: " + resources.getBackgroundPath());
            System.out.println("   前景: " + resources.getForegroundPath());
            System.out.println("   有背景: " + resources.hasBackground());
            System.out.println("   有前景: " + resources.hasForeground());
            
        } catch (Exception e) {
            System.err.println("❌ 提取前景图片失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 处理9-patch图片，移除9-patch标记
     */
    private static BufferedImage processNinePatchImage(BufferedImage ninePatchImage) {
        int width = ninePatchImage.getWidth();
        int height = ninePatchImage.getHeight();
        
        // 移除9-patch的1像素边框
        BufferedImage processedImage = new BufferedImage(width - 2, height - 2, BufferedImage.TYPE_INT_ARGB);
        
        // 复制内容区域（跳过边框）
        for (int y = 1; y < height - 1; y++) {
            for (int x = 1; x < width - 1; x++) {
                int pixel = ninePatchImage.getRGB(x, y);
                processedImage.setRGB(x - 1, y - 1, pixel);
            }
        }
        
        return processedImage;
    }
    
    /**
     * 放大图片用于查看细节
     */
    private static BufferedImage enlargeImage(BufferedImage originalImage, int scale) {
        int newWidth = originalImage.getWidth() * scale;
        int newHeight = originalImage.getHeight() * scale;
        
        BufferedImage enlargedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
        
        for (int y = 0; y < newHeight; y++) {
            for (int x = 0; x < newWidth; x++) {
                int originalX = x / scale;
                int originalY = y / scale;
                int pixel = originalImage.getRGB(originalX, originalY);
                enlargedImage.setRGB(x, y, pixel);
            }
        }
        
        return enlargedImage;
    }
}
